package com.zhan.signalling.util;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.redisson.api.RBucket;
import org.redisson.api.RSetCache;
import org.redisson.api.RedissonClient;

import com.google.common.collect.Maps;

public class RedisUtil {
	
	public static Map<String,Set<String>> forbiddenWordMap = Maps.newHashMap();
	
	public static Map<String,Set<String>> kickOutMap = Maps.newHashMap();
	
	public static Map<String,Long> lastSeqIdMap = Maps.newConcurrentMap();
	
	private static RedissonClient redissonClient;
	
	public static void init(RedissonClient redissonClient) {
		RedisUtil.redissonClient = redissonClient;
	}
	
	public static void addForbiddenWord(String groupId, String userId) {
		RSetCache<String> forbiddenWordList = redissonClient.getSetCache(groupId + ":ForbiddenWord");
		if(!forbiddenWordList.isExists()) {
			forbiddenWordList.expire(1, TimeUnit.DAYS);
		}
		forbiddenWordList.add(userId);
	}
	
	public static boolean isForbiddenWord(String groupId, String userId) {
		RSetCache<String> forbiddenWordList = redissonClient.getSetCache(groupId + ":ForbiddenWord");
		if(!forbiddenWordList.isExists()) {
			return false;
		}
		if(forbiddenWordList.contains(userId)) {
			return true;
		}
		return false;
		
	}
	
	public static void removeForbiddenWord(String groupId, String userId) {
		RSetCache<String> forbiddenWordList = redissonClient.getSetCache(groupId + ":ForbiddenWord");
		if(forbiddenWordList.isExists()) {
			forbiddenWordList.remove(userId);
		}
	}
	
	public static void addKickOut(String groupId, String userId) {
		RSetCache<String> kickOutList = redissonClient.getSetCache(groupId + ":KickOut");
		if(!kickOutList.isExists()) {
			kickOutList.expire(1, TimeUnit.DAYS);
		}
		kickOutList.add(userId);
	}
	
	public static boolean isKickOut(String groupId, String userId) {
		RSetCache<String> kickOutList = redissonClient.getSetCache(groupId + ":KickOut");
		if(!kickOutList.isExists()) {
			return false;
		}
		if(kickOutList.contains(userId)) {
			return true;
		}
		return false;
		
	}
	
	public static void removeKickOut(String groupId, String userId) {
		RSetCache<String> kickOutList = redissonClient.getSetCache(groupId + ":KickOut");
		if(kickOutList.isExists()) {
			kickOutList.remove(userId);
		}
	}
	
	public static void addLastSeqId(String groupId, long seqId) {
		RBucket<Long> lastSeqId =  redissonClient.getBucket(groupId + ":LastSeqId");
		if(!lastSeqId.isExists()) {
			lastSeqId.expire(1, TimeUnit.DAYS);
		}
		lastSeqId.set(seqId);
	}
	
	public static long lastSeqId(String groupId) {
		RBucket<Long> lastSeqId =  redissonClient.getBucket(groupId + ":LastSeqId");
		if(lastSeqId.isExists()) {
			return lastSeqId.get();
		}
		return 0;
	}

}
